<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\User;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Session;

class LoginController extends CommonController
{
    /**
     *  登录
     */
    public function login()
    {
        if ($input = Input::all()) {
            $code = $input['code'];
            if (Session::get('milkcaptcha') != $code) {
                //用户输入验证码正确
                return back()->with('msg','您输入验证码有误!');
            }
            $user = User::first();
            if ($user->user_name != $input['username'] ||
                Crypt::decrypt($user->user_pass) != $input['password']) {
                return back()->with('msg', '用户名或密码错误！');
            }
            // 把用户信息写入 session 中
            session(['user' => $user]);
            // 跳转到后台首页
            return redirect('admin/index');
        } else {


            return view('admin/login');
        }
    }

    /**
     * 创建验证码
     * @return mixed
     */
    public function captcha()
    {
        $builder = new CaptchaBuilder();
        $builder->build(110, 32);
        $phrase = $builder->getPhrase();
        //把内容存入session
        Session::flash('milkcaptcha', $phrase); //存储验证码
        ob_clean();
        return response($builder->output())->header('Content-type','image/jpeg');
    }

    public function quit()
    {
        session(['user' => null]);
        return redirect('admin/login');
    }

    // 测试
    public function crypt()
    {
        $str = '123456';
        $str_p = 'eyJpdiI6IjNJYmZ1aVZSN1BoYnkzOHJXaHFlcUE9PSIsInZhbHVlIjoiR3Y4NVY1Yjl6QmlZVlNtb0RzWGdodz09IiwibWFjIjoiNTczNjc1MDlkODE2NDgwYzUxODFiZTg3YzZjNzg1NDg0OTFhNThmNzcwZTM3ODE4M2Q3NTMyMDBmNTdkYjljYSJ9';
        echo Crypt::encrypt($str);
        echo '<br/>';
        echo Crypt::decrypt($str_p);

    }
}
